<!DOCTYPE html>
<html class="has-navbar-fixed-top">
<head>
    <meta charset="utf-8">
<title>Python下GDAL和OGR的使用 - wanzixin</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/outdated-browser/1.1.5/outdatedbrowser.min.css">


<link href="/zh-cn/Item/Python%E4%B8%8BGDAL%E5%92%8COGR%E7%9A%84%E4%BD%BF%E7%94%A8/" rel="alternate" hreflang="zh-CN" />
    


<meta name="description" content="">





    <meta name="description" content="项目上需要实现两个功能，一个是shp文件（路网）与tif文件（积水）的相交，以获取各条道路的积水信息；一个是根据经纬度位置获取对应tif文件的像素值。某个项目上需要实现两个功能，一个是shp文件（路网）与tif文件（积水）的相交，以获取各条道路的积水信息；一个是根据经纬度位置获取对应tif文件的像素值。为了解决上述问题，首先考虑到ArcGIS Desktop自带的ArcPy，">
<meta property="og:type" content="article">
<meta property="og:title" content="Python下GDAL和OGR的使用">
<meta property="og:url" content="https://wanzixin.github.io/Item/Python%E4%B8%8BGDAL%E5%92%8COGR%E7%9A%84%E4%BD%BF%E7%94%A8/index.html">
<meta property="og:site_name" content="wanzixin">
<meta property="og:description" content="项目上需要实现两个功能，一个是shp文件（路网）与tif文件（积水）的相交，以获取各条道路的积水信息；一个是根据经纬度位置获取对应tif文件的像素值。某个项目上需要实现两个功能，一个是shp文件（路网）与tif文件（积水）的相交，以获取各条道路的积水信息；一个是根据经纬度位置获取对应tif文件的像素值。为了解决上述问题，首先考虑到ArcGIS Desktop自带的ArcPy，">
<meta property="og:locale" content="en_US">
<meta property="og:image" content="https://img.shields.io/badge/python-3.8-blue.svg">
<meta property="article:published_time" content="2020-08-09T15:07:11.000Z">
<meta property="article:modified_time" content="2021-05-30T14:23:13.032Z">
<meta property="article:author" content="wanzixin">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img.shields.io/badge/python-3.8-blue.svg">





<link rel="icon" href="/favicon.png">


<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Ovo|Source+Code+Pro">
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bulma/0.6.2/css/bulma.min.css">


<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/lightgallery/1.6.8/css/lightgallery.min.css">
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/justifiedGallery/3.6.5/css/justifiedGallery.min.css">


<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/atom-one-light.min.css">


<link rel="stylesheet" href="/css/style.css">


<script defer src="//use.fontawesome.com/releases/v5.0.8/js/all.js"></script>


    
    
    
    
    
    
    
    
    
    

    


<meta name="generator" content="Hexo 5.4.0"></head>
<body>
    
<nav class="navbar is-transparent is-fixed-top navbar-main" role="navigation" aria-label="main navigation">
    <div class="container">
        <div class="navbar-brand">
            <a class="navbar-item navbar-logo" href="/">
                
                    
                    wanzixin
                    
                
            </a>
            <div class="navbar-burger">
                <span></span>
                <span></span>
                <span></span>
            </div>
        </div>
        
        <div class="navbar-menu navbar-start">
            
            <a class="navbar-item "
               href="/archives">Archives</a>
            
            <a class="navbar-item "
               href="/categories">Categories</a>
            
            <a class="navbar-item "
               href="/categories/Diary">Diary</a>
            
            <a class="navbar-item "
               href="/categories/Gallery">Gallery</a>
            
            <a class="navbar-item "
               href="/categories/Study">Study</a>
            
            <a class="navbar-item "
               href="/categories/Item">Item</a>
            
            <a class="navbar-item "
               href="/about">About</a>
            
        </div>
        
        <div class="navbar-menu navbar-end">
            
            <a class="navbar-item search" title="Search" href="javascript:;">
                <i class="fas fa-search"></i>
            </a>
            
            
            <div class="navbar-item is-hoverable has-dropdown is-hidden-mobile is-hidden-tablet-only toc">
                <a class="navbar-item" title="Table of Contents">
                    <i class="fa fa-list"></i>
                </a>
                <div class="navbar-dropdown is-right">
                    
                    
                    
                    
                    <a class="navbar-item" href="#GDAL和OGR的安装">1&nbsp;&nbsp;<b>GDAL和OGR的安装</b></a>
                    
                    
                    <hr class="navbar-divider">
                    
                    
                    <a class="navbar-item" href="#GDAL和OGR的使用">2&nbsp;&nbsp;<b>GDAL和OGR的使用</b></a>
                    
                    
                    
                    <a class="navbar-item" href="#栅格数据的读取">2.1&nbsp;&nbsp;栅格数据的读取</a>
                    
                    
                    
                    <a class="navbar-item" href="#矢量数据的读取">2.2&nbsp;&nbsp;矢量数据的读取</a>
                    
                    
                    
                    <a class="navbar-item" href="#栅格矢量化">2.3&nbsp;&nbsp;栅格矢量化</a>
                    
                    
                    
                    <a class="navbar-item" href="#栅格数据中根据仿射信息将经纬度转换为行列号">2.4&nbsp;&nbsp;栅格数据中根据仿射信息将经纬度转换为行列号</a>
                    
                    
                    
                    <a class="navbar-item" href="#矢量数据的相交Intersect">2.5&nbsp;&nbsp;矢量数据的相交Intersect</a>
                    
                    
                    
                    <a class="navbar-item" href="#图层空间参考的修改">2.6&nbsp;&nbsp;图层空间参考的修改</a>
                    
                    
                    <hr class="navbar-divider">
                    
                    
                    <a class="navbar-item" href="#结语">3&nbsp;&nbsp;<b>结语</b></a>
                    
                </div>
            </div>
            
            
            <a class="navbar-item" title="GitHub" target="_blank" rel="noopener" href="https://github.com/wanzixin">
                
                <i class="fab fa-github"></i>
                
            </a>
               
            
        </div>
    </div>
</nav>

    <section class="section">
    <div class="container">
    <article class="article content gallery" itemscope itemprop="blogPost">
    <h1 class="article-title is-size-3 is-size-4-mobile" itemprop="name">
        
            Python下GDAL和OGR的使用
        
    </h1>
    <div class="article-meta columns is-variable is-1 is-multiline is-mobile is-size-7-mobile">
        <span class="column is-narrow">
            
                <span>Aug 9 2020</span>
            
        </span>
        
        <span class="column is-narrow article-category">
            <i class="far fa-folder"></i>
            <a class="article-category-link" href="/categories/Item/">Item</a>
        </span>
        
        
        <span class="column is-narrow">
            
            
            13 minutes read (About 1961 words)
        </span>
        
    </div>
    <div class="article-entry is-size-6-mobile" itemprop="articleBody">
    
        <html><head></head><body><p><img src="https://img.shields.io/badge/python-3.8-blue.svg"></p>
<p>项目上需要实现两个功能，一个是shp文件（路网）与tif文件（积水）的相交，以获取各条道路的积水信息；一个是根据经纬度位置获取对应tif文件的像素值。某个项目上需要实现两个功能，一个是shp文件（路网）与tif文件（积水）的相交，以获取各条道路的积水信息；一个是根据经纬度位置获取对应tif文件的像素值。为了解决上述问题，首先考虑到ArcGIS Desktop自带的ArcPy，<span id="more"></span>借助ArcPy可以调用标准工具箱的任意一项工具，但最大的缺点在于速度，仅仅在import语句中导入ArcPy模块，就需要花费十秒左右的时间，而且Python2.7的版本太过远古。如果仅仅是做单独脚本，或者是编写ArcGIS的脚本工具，ArcPy仍然是最好的选择。但要考虑到作为Web服务，时延太长就很不合理了。因而，选择了Python 3.8环境下的gdal和ogr，分别用于处理栅格数据和矢量数据；使用flask和flasgger，分别用于微型网络框架和Swagger-UI的使用。</p>
<h2 id="GDAL和OGR的安装"><a href="#GDAL和OGR的安装" class="headerlink" title="GDAL和OGR的安装"></a>GDAL和OGR的安装</h2><p>使用pip安装速度上很慢，使用国内镜像源速度快很多，共有两种方式在pip安装模块时使用镜像源。</p>
<ul>
<li><p>临时修改。使用pip时加上<code>-i https://pypi.tuna.tsinghua.edu.cn/simple</code>，例如：<code>pip install gdal -i https://pypi.tuna.tsinghua.edu.cn/simple</code>即使用了清华的镜像源。</p>
</li>
<li><p>永久修改。Windows平台下的用户目录新建pip文件夹，再新建pip.ini配置文件，写入如下内容保存，以后的每次pip安装模块都会使用阿里云的镜像源了。</p>
<figure class="highlight plaintext hljs"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs plaintext">[global]<br>index-url = http://mirrors.aliyun.com/pypi/simple/<br>[install]<br>trusted-host = mirrors.aliyun.com<br></code></pre></td></tr></tbody></table></figure>

<p>使用<code>pip install gdal</code>命令即可，因为gdal和ogr都被集成在了osgeo中，ogr也会一并下载。使用<code>from osgeo import gdal, ogr</code>即可导入。</p>
</li>
</ul>
<h2 id="GDAL和OGR的使用"><a href="#GDAL和OGR的使用" class="headerlink" title="GDAL和OGR的使用"></a>GDAL和OGR的使用</h2><p>Python下GDAL的官方文档，地址为<a target="_blank" rel="noopener" href="https://gdal.org/python">https://gdal.org/python</a>，以下将本次任务中使用到的部分做个简单的记录。</p>
<h3 id="栅格数据的读取"><a href="#栅格数据的读取" class="headerlink" title="栅格数据的读取"></a>栅格数据的读取</h3><figure class="highlight python hljs"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">from</span> osgeo <span class="hljs-keyword">import</span> gdal<br><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">readRaster</span>(<span class="hljs-params">rasterPath</span>):</span><br>    dataset = gdal.Open(rasterPath)<br>    <span class="hljs-comment">#波段从1开始计数，这行语句获取栅格数据集的第二个波段</span><br>    band2 = dataset.GetRasterBand(<span class="hljs-number">2</span>) <br>    <span class="hljs-comment">#获取栅格文件的仿射信息，是一个包含六个元素的数组,第三个元素和第五个元素带代表旋转信息，一般都为0</span><br>    geotransform = dataset.GetGeoTransform() <br>    originX = geotransform[<span class="hljs-number">0</span>] <span class="hljs-comment">#左上角经度</span><br>    originY = geotransform[<span class="hljs-number">3</span>] <span class="hljs-comment">#左上角纬度</span><br>    pixelWidth = geotransform[<span class="hljs-number">1</span>] <span class="hljs-comment">#像元宽度</span><br>    pixelHeight = geotransform[<span class="hljs-number">5</span>] <span class="hljs-comment">#像元高度</span><br></code></pre></td></tr></tbody></table></figure>

<h3 id="矢量数据的读取"><a href="#矢量数据的读取" class="headerlink" title="矢量数据的读取"></a>矢量数据的读取</h3><figure class="highlight python hljs"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">from</span> osgeo <span class="hljs-keyword">import</span> ogr<br><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">readShp</span>(<span class="hljs-params">shpPath</span>):</span><br>    driver = ogr.GetDriverByName(<span class="hljs-string">'ESRI Shapefile'</span>)<br>    ds = driver.Open(shppath, <span class="hljs-number">0</span>) <span class="hljs-comment"># read only</span><br>    layer = ds.GetLayer(<span class="hljs-number">0</span>) <span class="hljs-comment">#获取数据集的第一个图层</span><br>    ds_sr = layer.GetSpatialRef() <span class="hljs-comment">#获取数据集的空间参考</span><br>    <br>    <span class="hljs-comment">#获取图层的每一个要素与属性</span><br>    <span class="hljs-keyword">for</span> feature <span class="hljs-keyword">in</span> layer:<br>        geomtry = feature.GetGeometryRef()<br>        FID = feature.GetField(<span class="hljs-string">'FID'</span>)<br></code></pre></td></tr></tbody></table></figure>

<h3 id="栅格矢量化"><a href="#栅格矢量化" class="headerlink" title="栅格矢量化"></a>栅格矢量化</h3><figure class="highlight python hljs"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">raster_to_shapefile</span>(<span class="hljs-params">self,rasterpath</span>):</span><br>    driver = ogr.GetDriverByName(<span class="hljs-string">'ESRI Shapefile'</span>)<br>    src_dataset = gdal.Open(rasterpath)<br><br>    <span class="hljs-comment"># get band2 in tif</span><br>    src_band2 = src_dataset.GetRasterBand(<span class="hljs-number">2</span>)<br>    maskband = src_band2.GetMaskBand() <span class="hljs-comment">#掩膜波段图层</span><br><br>    target_sr = osr.SpatialReference()<br>    target_sr.ImportFromEPSG(<span class="hljs-number">4326</span>)<br><br>    dst_layerName = <span class="hljs-string">"byproduct/Polyginize_Stuff"</span><br>    dst_dateset = driver.CreateDataSource(dst_layerName + <span class="hljs-string">".shp"</span>)<br>    dst_layer = dst_dateset.CreateLayer(dst_layerName, srs = target_sr)<br><br>    <span class="hljs-comment"># DN代表地物反射率，这段代码在属性表创建了DN列，值即为波段2的值</span><br>    dst_fieldName = <span class="hljs-string">'DN'</span><br>    fd = ogr.FieldDefn(dst_fieldName, ogr.OFTInteger)<br>    dst_layer.CreateField(fd)<br><br>    <span class="hljs-comment"># 第四个参数是需要将DN值写入矢量字段的索引，应该不包括FID和Shape</span><br>    gdal.Polygonize(src_band2, maskband, dst_layer, <span class="hljs-number">0</span>, [], callback = <span class="hljs-literal">None</span>) <br>    <span class="hljs-keyword">return</span> dst_layerName<br></code></pre></td></tr></tbody></table></figure>

<h3 id="栅格数据中根据仿射信息将经纬度转换为行列号"><a href="#栅格数据中根据仿射信息将经纬度转换为行列号" class="headerlink" title="栅格数据中根据仿射信息将经纬度转换为行列号"></a>栅格数据中根据仿射信息将经纬度转换为行列号</h3><figure class="highlight python hljs"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">getRGBByLnglat</span>(<span class="hljs-params">self,lnglat,time</span>):</span><br>    maxTifpath = self.getMaxTifpathByTime(time)<br>    dataset = gdal.Open(maxTifpath)<br><br>    geotransform = dataset.GetGeoTransform()<br>    originX = geotransform[<span class="hljs-number">0</span>]<br>    originY = geotransform[<span class="hljs-number">3</span>]<br>    pixelWidth = geotransform[<span class="hljs-number">1</span>]<br>    pixelHeight = geotransform[<span class="hljs-number">5</span>]<br><br>    xOffset = <span class="hljs-built_in">int</span>((lnglat[<span class="hljs-number">0</span>]-originX)/pixelWidth)<br>    yOffset = <span class="hljs-built_in">int</span>((lnglat[<span class="hljs-number">1</span>]-originY)/pixelHeight)<br><br>    rgb = []<br>    <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-number">1</span>,<span class="hljs-number">4</span>):<br>        band = dataset.GetRasterBand(i)<br>        <span class="hljs-comment"># gridcode is a two-dimensional array with only an element</span><br>        gridcode = band.ReadAsArray(xOffset,yOffset,<span class="hljs-number">1</span>,<span class="hljs-number">1</span>) <br>        rgb.append(gridcode[<span class="hljs-number">0</span>][<span class="hljs-number">0</span>])<br>    <span class="hljs-keyword">return</span> <span class="hljs-built_in">str</span>(rgb[<span class="hljs-number">0</span>]) + <span class="hljs-string">','</span> + <span class="hljs-built_in">str</span>(rgb[<span class="hljs-number">1</span>]) + <span class="hljs-string">','</span> + <span class="hljs-built_in">str</span>(rgb[<span class="hljs-number">2</span>])<br></code></pre></td></tr></tbody></table></figure>

<h3 id="矢量数据的相交Intersect"><a href="#矢量数据的相交Intersect" class="headerlink" title="矢量数据的相交Intersect"></a>矢量数据的相交Intersect</h3><p>在ogr中，读入一个矢量文件得到的是数据集，数据集的下一维度是图层（一般只有一个图层），图层的下一维度是要素，要素包含几何图形和属性。相交有两个维度的判断办法，一种是Layer（图层）的相交，一种是Geometry（几何图形）的相交。基于Layer的相交仅有一个函数Intersection，无论是否存在相交，返回的都是处理结果；而基于Geometry的相交则有三个函数，分别是Intersection，Intersect，Intersects，不同点在于后两个函数返回的是bool值，即只要几何图形的envelope重叠就返回True，否则返回False。</p>
<figure class="highlight python hljs"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">getDataSetFromShpPath</span>(<span class="hljs-params">self, shppath</span>):</span><br>    driver = ogr.GetDriverByName(<span class="hljs-string">'ESRI Shapefile'</span>)<br>    ds = driver.Open(shppath, <span class="hljs-number">0</span>) <span class="hljs-comment"># read only</span><br>    <span class="hljs-keyword">if</span> ds <span class="hljs-keyword">is</span> <span class="hljs-literal">None</span>:<br>        <span class="hljs-built_in">print</span>(shppath + <span class="hljs-string">'is wrong.'</span>)<br>        <span class="hljs-keyword">return</span><br>    <span class="hljs-keyword">return</span> ds<br><br><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">intersectTwoShp</span>(<span class="hljs-params">roadShp,pondshp</span>):</span><br>    pond_ds = getDataSetFromShpPath(pondshp)<br>    road_ds = getDataSetFromShpPath(roadShp)<br><br>    pond_layer = pond_ds.GetLayer(<span class="hljs-number">0</span>)<br>    road_layer = road_ds.GetLayer(<span class="hljs-number">0</span>)<br><br>    <span class="hljs-comment"># 用于空间参考的一致性变换</span><br>    src_sr = road_layer.GetSpatialRef()<br>    target_sr = pond_layer.GetSpatialRef()<br>    ct = osr.CoordinateTransformation(src_sr,target_sr)<br><br>    infos = [] <span class="hljs-comment"># 构建的相交信息</span><br>    i = <span class="hljs-number">0</span> <span class="hljs-comment"># 总循环次数</span><br>    j = <span class="hljs-number">0</span> <span class="hljs-comment"># 相交次数</span><br>    <span class="hljs-keyword">for</span> pond_feature <span class="hljs-keyword">in</span> pond_layer:<br>        pond_geom = pond_feature.GetGeometryRef()<br>        <span class="hljs-keyword">for</span> road_feature <span class="hljs-keyword">in</span> road_layer:<br>            i += <span class="hljs-number">1</span><br>            road_geom = road_feature.GetGeometryRef()<br>            road_geom.Transform(ct)<br>            intersect = pond_geom.Intersect(road_geom)<br>            <span class="hljs-keyword">if</span> intersect:<br>                <span class="hljs-comment"># 以下为提取信息，可以根据需要做替换或是修改</span><br>                j += <span class="hljs-number">1</span><br>                info = {}<br>                road_id = road_feature.GetField(<span class="hljs-string">'road_id'</span>)<br>                name = road_feature.GetField(<span class="hljs-string">'name'</span>)<br>                gridCode = pond_feature.GetField(<span class="hljs-string">'DN'</span>)<br>                g_legend = self._getLegend(gridCode)<br>                g_code = self._getLevelType(g_legend)<br><br>                <span class="hljs-keyword">if</span> g_legend &lt; <span class="hljs-number">0.1</span>:<br>                    <span class="hljs-keyword">continue</span><br><br>                info[<span class="hljs-string">"level"</span>] = g_legend<br>                info[<span class="hljs-string">"levelType"</span>] = g_code<br>                info[<span class="hljs-string">"name"</span>] = name<br>                info[<span class="hljs-string">"road_id"</span>] = road_id<br>                infos.append(info)<br>	<span class="hljs-comment"># print(i,j)</span><br>    infos_new = _reviseInfos(infos)<br>    <span class="hljs-keyword">return</span> infos_new<br><br><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">_reviseInfos</span>(<span class="hljs-params">infos</span>):</span><br>    <span class="hljs-comment"># 按road_id排序</span><br>    infos.sort(key=<span class="hljs-keyword">lambda</span> x: x[<span class="hljs-string">'road_id'</span>])<br>    <span class="hljs-comment"># 设置一个哨兵字典,初值为列表第一个元素</span><br>    info_flag = {}<br>    info_flag = infos[<span class="hljs-number">0</span>]<br>    <span class="hljs-comment"># 定义一个新列表，作返回值</span><br>    infos_new = []<br>    infos_new.append(info_flag)<br>    <span class="hljs-comment"># 从列表第二个元素开始</span><br>    i = <span class="hljs-number">1</span> <br>    <span class="hljs-keyword">while</span> i &lt; <span class="hljs-built_in">len</span>(infos):<br>        <span class="hljs-keyword">if</span>(info_flag[<span class="hljs-string">'road_id'</span>] == infos[i][<span class="hljs-string">'road_id'</span>]):<br>             <span class="hljs-comment"># info_max是待返回列表的最后一个元素,定义一个info_max存储road_id相等中level最大的字典元素</span><br>            info_max = infos_new[-<span class="hljs-number">1</span>]<br>            <span class="hljs-keyword">if</span>(info_max[<span class="hljs-string">'level'</span>] &lt; infos[i][<span class="hljs-string">'level'</span>]):<br>                info_max = infos[i]<br>                infos_new.pop(-<span class="hljs-number">1</span>)<br>                infos_new.append(info_max)<br>                <span class="hljs-keyword">else</span>:<br>                    infos_new.append(infos[i])<br><br>             info_flag = infos[i]<br>             i += <span class="hljs-number">1</span><br><br>    <span class="hljs-keyword">return</span> infos_new<br></code></pre></td></tr></tbody></table></figure>

<h3 id="图层空间参考的修改"><a href="#图层空间参考的修改" class="headerlink" title="图层空间参考的修改"></a>图层空间参考的修改</h3><p>这个部分在2.5节中有应用，在这里主要是在Geometry级别的操作，在DataSet类中有Set SpatialRef函数可以实现数据集的空间参考修改。</p>
<figure class="highlight python hljs"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">from</span> osgeo <span class="hljs-keyword">import</span> ogr,osr<br><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">modifySR</span>(<span class="hljs-params">srcShpPath, targetShpPath</span>)</span><br><span class="hljs-function">    <span class="hljs-title">road_ds</span> = <span class="hljs-title">self</span>.<span class="hljs-title">getDataSetFromShpPath</span>(<span class="hljs-params">srcShpPath</span>)</span><br><span class="hljs-function">    <span class="hljs-title">pond_ds</span> = <span class="hljs-title">self</span>.<span class="hljs-title">getDataSetFromShpPath</span>(<span class="hljs-params">targetShpPath</span>)</span><br><span class="hljs-function"></span><br><span class="hljs-function">    <span class="hljs-title">road_layer</span> = <span class="hljs-title">road_ds</span>.<span class="hljs-title">GetLayer</span>(<span class="hljs-params"><span class="hljs-number">0</span></span>)</span><br><span class="hljs-function">    <span class="hljs-title">pond_layer</span> = <span class="hljs-title">pond_ds</span>.<span class="hljs-title">GetLayer</span>(<span class="hljs-params"><span class="hljs-number">0</span></span>)</span><br><span class="hljs-function"></span><br><span class="hljs-function">    <span class="hljs-title">src_sr</span> = <span class="hljs-title">road_layer</span>.<span class="hljs-title">GetSpatialRef</span>()</span><br><span class="hljs-function">    <span class="hljs-title">target_sr</span> = <span class="hljs-title">pond_layer</span>.<span class="hljs-title">GetSpatialRef</span>()</span><br><span class="hljs-function">    <span class="hljs-title">ct</span> = <span class="hljs-title">osr</span>.<span class="hljs-title">CoordinateTransformation</span>(<span class="hljs-params">src_sr,target_sr</span>)</span><br><span class="hljs-function">    </span><br><span class="hljs-function">    # <span class="hljs-title">Geometry</span>级别的修改空间参考，但图层本身并没有被修改</span><br><span class="hljs-function">    <span class="hljs-title">for</span> <span class="hljs-title">feature</span> <span class="hljs-title">in</span> <span class="hljs-title">road_layer</span>:</span><br>        geom = feature.GetGeometryReF()<br>        geom.Transform(ct)<br></code></pre></td></tr></tbody></table></figure>

<h2 id="结语"><a href="#结语" class="headerlink" title="结语"></a>结语</h2><p>最终的版本还有一些可以修改的地方，不是尽善尽美的，主要因为对gdal和ogr本身的类结构不熟悉。</p>
<p>在使用过程中参考了很多CSDN的博客，起了个入门的作用。如果真想要深入的使用gdal和ogr这么强大的工具，应该研究官方给出的文档，关键函数都有详细的说明，查看传入参数、返回值和函数名基本上能猜个八九不离十。另外，类图的阅读非常有必要，这可以帮助快速的掌握模块的组织架构，总的来说有所收获。</p>
<p>看得开心！</p>
</body></html>
    
    </div>
    
    
    <div class="columns is-mobile is-multiline article-nav">
        <span class="column is-12-mobile is-half-desktop  article-nav-prev">
            
            <a href="/Study/PostgreSQL%E5%B8%B8%E7%94%A8%E5%91%BD%E4%BB%A4%E8%AE%B0%E5%BD%95/">PostgreSQL常用命令记录</a>
            
        </span>
        <span class="column is-12-mobile is-half-desktop  article-nav-next">
            
            <a href="/Item/ArcGIS%E4%B8%AD%E8%87%AA%E5%AE%9A%E4%B9%89Python%E8%84%9A%E6%9C%AC%E5%B7%A5%E5%85%B7/">ArcGIS中自定义Python脚本工具</a>
            
        </span>
    </div>
    
</article>


<div class="sharebox">
    
<div class="sharethis-inline-share-buttons"></div>
<script type='text/javascript' src='//platform-api.sharethis.com/js/sharethis.js#property=608c1408daac690012507aa2&amp;product=sop' async='async'></script>

</div>



    </div>
</section>
    <footer class="footer">
    <div class="container">
        <div class="columns content">
            <div class="column is-narrow has-text-centered">
                &copy; 2021 wanzixin&nbsp;
                Powered by <a href="http://hexo.io/" target="_blank">Hexo</a> & <a
                        target="_blank" rel="noopener" href="http://github.com/ppoffice/hexo-theme-minos">Minos</a>
            </div>
            <div class="column is-hidden-mobile"></div>

            
            <div class="column is-narrow">
                <div class="columns is-mobile is-multiline is-centered">
                
                    
                <a class="column is-narrow has-text-black" title="GitHub" target="_blank" rel="noopener" href="https://github.com/ppoffice/hexo-theme-minos">
                    
                    GitHub
                    
                </a>
                
                </div>
            </div>
            
            
<div class="column is-narrow has-text-centered">
    <div class="dropdown is-up is-right is-hoverable" style="margin-top: -0.2em;">
        <div class="dropdown-trigger">
            <button class="button is-small" aria-haspopup="true" aria-controls="dropdown-menu7">
                <span class="icon">
                    <i class="fas fa-globe"></i>
                </span>
                <span>English</span>
                <span class="icon is-small">
            <i class="fas fa-angle-down" aria-hidden="true"></i>
          </span>
            </button>
        </div>
        <div class="dropdown-menu has-text-left" role="menu">
            <div class="dropdown-content">
            
                <a href="/Item/Python%E4%B8%8BGDAL%E5%92%8COGR%E7%9A%84%E4%BD%BF%E7%94%A8/" class="dropdown-item">
                    English
                </a>
            
                <a href="/zh-cn/Item/Python%E4%B8%8BGDAL%E5%92%8COGR%E7%9A%84%E4%BD%BF%E7%94%A8/" class="dropdown-item">
                    简体中文
                </a>
            
            </div>
        </div>
    </div>
</div>

        </div>
    </div>
</footer>
    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment-with-locales.min.js"></script>

<!-- test if the browser is outdated -->
<div id="outdated">
    <h6>Your browser is out-of-date!</h6>
    <p>Update your browser to view this website correctly. <a id="btnUpdateBrowser" target="_blank" rel="noopener" href="http://outdatedbrowser.com/">Update my browser now </a></p>
    <p class="last"><a href="#" id="btnCloseUpdateBrowser" title="Close">&times;</a></p>
</div>
<script src="//cdnjs.cloudflare.com/ajax/libs/outdated-browser/1.1.5/outdatedbrowser.min.js"></script>
<script>
    $(document).ready(function () {
        // plugin function, place inside DOM ready function
        outdatedBrowser({
            bgColor: '#f25648',
            color: '#ffffff',
            lowerThan: 'flex'
        })
    });
</script>

<script>
    window.FontAwesomeConfig = {
        searchPseudoElements: true
    }
    moment.locale("en-AU");
</script>


    
    
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/MathJax.js?config=TeX-MML-AM_CHTML"></script>
<script>
    MathJax.Hub.Config({
        "HTML-CSS": {
            matchFontHeight: false
        },
        SVG: {
            matchFontHeight: false
        },
        CommonHTML: {
            matchFontHeight: false
        },
        tex2jax: {
            inlineMath: [
                ['$','$'],
                ['\\(','\\)']
            ]
        }
    });
</script>

    
    
    
    
<script src="//cdnjs.cloudflare.com/ajax/libs/lightgallery/1.6.8/js/lightgallery-all.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/justifiedGallery/3.6.5/js/jquery.justifiedGallery.min.js"></script>
<script>
    (function ($) {
        $(document).ready(function () {
            if (typeof($.fn.lightGallery) === 'function') {
                $('.article.gallery').lightGallery({ selector: '.gallery-item' });
            }
            if (typeof($.fn.justifiedGallery) === 'function') {
                $('.justified-gallery').justifiedGallery();
            }
        });
    })(jQuery);
</script>

    
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.0/clipboard.min.js"></script>
    <style>
        .hljs {
            position: relative;
        }

        .hljs .clipboard-btn {
            float: right;
            color: #9a9a9a;
            background: none;
            border: none;
            cursor: pointer;
        }

        .hljs .clipboard-btn:hover {
          color: #8a8a8a;
        }

        .hljs > .clipboard-btn {
            display: none;
            position: absolute;
            right: 4px;
            top: 4px;
        }

        .hljs:hover > .clipboard-btn {
            display: inline;
        }

        .hljs > figcaption > .clipboard-btn {
            margin-right: 4px;
        }
    </style>
    <script>
      $(document).ready(function () {
        $('figure.hljs').each(function(i, figure) {
          var codeId = 'code-' + i;
          var code = figure.querySelector('.code');
          var copyButton = $('<button>Copy <i class="far fa-clipboard"></i></button>');
          code.id = codeId;
          copyButton.addClass('clipboard-btn');
          copyButton.attr('data-clipboard-target-id', codeId);

          var figcaption = figure.querySelector('figcaption');

          if (figcaption) {
            figcaption.append(copyButton[0]);
          } else {
            figure.prepend(copyButton[0]);
          }
        })

        var clipboard = new ClipboardJS('.clipboard-btn', {
          target: function(trigger) {
            return document.getElementById(trigger.getAttribute('data-clipboard-target-id'));
          }
        });
        clipboard.on('success', function(e) {
          e.clearSelection();
        })
      })
    </script>

    
    

    



<script src="/js/script.js"></script>


    
    <div class="searchbox ins-search">
    <div class="searchbox-mask"></div>
    <div class="searchbox-container ins-search-container">
        <div class="searchbox-input-wrapper">
            <input type="text" class="searchbox-input ins-search-input" placeholder="Type something..." />
            <span class="searchbox-close ins-close ins-selectable"><i class="fa fa-times-circle"></i></span>
        </div>
        <div class="searchbox-result-wrapper ins-section-wrapper">
            <div class="ins-section-container"></div>
        </div>
    </div>
</div>
<script>
    (function (window) {
        var INSIGHT_CONFIG = {
            TRANSLATION: {
                POSTS: 'Posts',
                PAGES: 'Pages',
                CATEGORIES: 'Categories',
                TAGS: 'Tags',
                UNTITLED: '(Untitled)',
            },
            CONTENT_URL: '/content.json',
        };
        window.INSIGHT_CONFIG = INSIGHT_CONFIG;
    })(window);
</script>

<script src="/js/insight.js"></script>

    
</body>
</html>